package ex_dbproduct;

import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.Vector;

import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableRowSorter;
import javax.swing.SpringLayout;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.SwingConstants;

import java.awt.Cursor;
import java.awt.GridLayout;
import java.awt.BorderLayout;

import javax.swing.JTextField;
import javax.swing.JLabel;

import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JScrollPane;
import javax.swing.JTable;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class SaleUpdate extends JInternalFrame {

	ProductMain5 m;
	SaleList sl;
	Connection con;
	String saNo;//판매번호
	String befo_ea;//기존 수량
	String saCode;//코드
	int saPrice;//금액
	SalStock st = new SalStock();
	DecimalFormat df = new DecimalFormat("###,###,###.##");
	
	
	private JPanel panel;
	private JPanel panel_1;
	private JTextField code;
	private JLabel lblNewLabel;
	private JLabel lblNewLabel_1;
	private JTextField codename;
	private JPanel panel_2;
	private JLabel label;
	private JTextField price;
	private JPanel panel_3;
	private JLabel label_1;
	private JTextField ea;
	private JPanel panel_4;
	private JButton btnNewButton;
	private JButton btnNewButton_1;
	private JPanel panel_5;
	private JScrollPane scrollPane;
	private JTable table;
	private JPanel panel_6;
	private JPanel panel_7;
	private JPanel panel_8;
	

	/**
	 * Create the frame.
	 */
	public SaleUpdate(ProductMain5 m, Connection c, SaleList s) {
		super("판매수정", true, true, true, false);
		this.m = m;
		this.con = c;
		this.sl = s;
		addInternalFrameListener(new InternalFrameAdapter() {
			@Override
			public void internalFrameClosing(InternalFrameEvent arg0) {
				sl.update = null;
			}
		});
		setBounds(100, 100, 471, 415);
		getContentPane().setLayout(new BorderLayout(0, 0));
		getContentPane().add(getPanel_7(), BorderLayout.NORTH);
		getContentPane().add(getPanel_8(), BorderLayout.CENTER);

	}

	public String replace(String s) {
		String temp = s.replace(",","");
		String temp2 = temp.replace("원","");
		return temp2;
	}

	public void setData(String sno, String c, String n, String p, String e) {
		this.saNo = sno;
		this.befo_ea = e;
		this.saCode = c;
		
		this.saPrice = Integer.parseInt(replace(p));
		code.setText(c);
		codename.setText(n);
		price.setText(p);
		ea.setText(e);
		
		setSelect();
	}
	
	public void mod(){

		String af_ea = JOptionPane.showInputDialog("판매량을 몇개로 수정하시겠습니까?", befo_ea);
		// 판매 디비 수정
		String sql = "update sale set sa_ea = ?, sa_price = ?, "
				+ "sa_mod_date = sysdate , sa_mod_mem = ? where sa_no = ?";
		int modPrice=(int)(saPrice*(Double.parseDouble(af_ea)/Double.parseDouble(befo_ea)));

		try {
			PreparedStatement pstmt = con.prepareStatement(sql);

			pstmt.setInt(1, Integer.parseInt(af_ea));
			pstmt.setInt(2, modPrice);
			pstmt.setString(3, m.member);
			pstmt.setString(4, saNo);

			pstmt.executeUpdate();
			pstmt.close();

			// 재고 수정 (매서드 실행)
			st.update(saCode, Integer.parseInt(befo_ea),Integer.parseInt(af_ea));

		} catch (SQLException se) {
			// TODO Auto-generated catch block
			se.printStackTrace();
		} catch (NumberFormatException ne) {
			// TODO Auto-generated catch block
			ne.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		befo_ea =af_ea;
		saPrice = modPrice;
		ea.setText(af_ea);
		price.setText(df.format(modPrice)+ "원");
		
		sl.search();// 조회버튼 다시 클릭
		
	}
	public void recall(){

		String sql;
		String re_ea = JOptionPane.showInputDialog("제품 몇개를 반품하시겠습니까?", befo_ea);
		int af_ea = Integer.parseInt(befo_ea) - Integer.parseInt(re_ea);
		
		try {
			PreparedStatement pstmt;
			if (re_ea.equals(befo_ea)) {
				int yn = JOptionPane.showConfirmDialog(null,
						"전체를 반품 하시겠습니까?");
				if(yn == JOptionPane.YES_OPTION){
				sql = "update sale set sa_recall = '1',sa_mod_date = sysdate, sa_mod_mem =? where sa_no=?";

				pstmt = con.prepareStatement(sql);
				pstmt.setString(1, m.member);
				pstmt.setString(2, saNo);
				pstmt.executeUpdate();
				pstmt.close();
				}
			} else {
				sql = "{call sale_recall(?, ?, ?, ?)}";//프로시저 실행!!

				pstmt = con.prepareStatement(sql);
				pstmt.setString(1, saNo);
				pstmt.setInt(2, af_ea);
				pstmt.setString(3, m.member);
				pstmt.setString(4, re_ea);
				pstmt.executeUpdate();
				pstmt.close();
			}
			//재고수정 매서드
			st.recall(saCode, Integer.parseInt(re_ea));
			sl.search();// 조회버튼 다시 클릭
			sl.update = null;
			dispose();
			JOptionPane.showMessageDialog(null, "반품 되었습니다.");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public void setSelect(){

		int count=0;//검색된 수
		int page=1;//페이지 번호
		int no =1;//글번호
		final int btnCnt = 5;
		
		String s = "Select sa_no 판매번호, sa_info 정보, in_de 수량, put_date 날짜, sa_mem 직원 from sale_history where sa_no = "+saNo+" order by put_date";
		try {
			PreparedStatement pstmt = con.prepareStatement(s);

			ResultSet rs = pstmt.executeQuery();

			// 컬럼명 테이블에 셋팅
			ResultSetMetaData rsm = rs.getMetaData();
			Vector col = new Vector<>();
			for(int i=1; i<=rsm.getColumnCount(); i++){
				col.add(rsm.getColumnName(i));
			}
			DefaultTableModel model = new DefaultTableModel(col, 0);
			table.setModel(model);
			
			

			table.setRowSorter(new TableRowSorter(model));
			DefaultTableCellRenderer Center = new DefaultTableCellRenderer();
			DefaultTableCellRenderer Right = new DefaultTableCellRenderer();
			TableColumnModel tcmSchedule = table.getColumnModel();
			table.getTableHeader().setReorderingAllowed(false);
			table.getTableHeader().setResizingAllowed(false);
			Center.setHorizontalAlignment(SwingConstants.CENTER);// 우측 정렬
			Right.setHorizontalAlignment(SwingConstants.RIGHT);// / 우측
			
			tcmSchedule.getColumn(0).setPreferredWidth(40);
			tcmSchedule.getColumn(1).setPreferredWidth(30);
			tcmSchedule.getColumn(2).setPreferredWidth(30);
			tcmSchedule.getColumn(3).setPreferredWidth(100);
			tcmSchedule.getColumn(4).setPreferredWidth(30);
			tcmSchedule.getColumn(0).setCellRenderer(Center);
			tcmSchedule.getColumn(1).setCellRenderer(Center);
			tcmSchedule.getColumn(2).setCellRenderer(Center);
			tcmSchedule.getColumn(4).setCellRenderer(Center);
			
			
			
			while(rs.next()){
				Vector row = new Vector<>();
				no++;
				if(no<=btnCnt+1){
				for(int i=1; i<=rsm.getColumnCount();i++){
					row.add(rs.getString(i));
				}
				model.addRow(row);}
				if(count%(btnCnt)==0||count==0){
					final JLabel lbl = new JLabel("("+page+")");
					
					lbl.addMouseListener(new MouseAdapter() {
						@Override
						public void mouseReleased(MouseEvent arg0) {
							String pos = lbl.getText();
							int k = Integer.parseInt(pos.substring(1, 2));
							pageList(k,btnCnt);
						}
						@Override
						public void mouseEntered(MouseEvent arg1){
							lbl.setCursor(new Cursor(Cursor.HAND_CURSOR));
						}
						@Override
						public void mouseExited(MouseEvent arg2){
							lbl.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
							
						}
					});
					
					panel_6.add(lbl);
					page++;
				}
				count++;
			}		

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}
	
	public void pageList(int k,int btnCnt){
		int pageCount=0;
		String s = "Select sa_no 판매번호, sa_info 정보, in_de 수량, put_date 날짜, sa_mem 직원 from sale_history where sa_no = "+saNo+" order by put_date";
		
		try {
			PreparedStatement pstmt = con.prepareStatement(s);

			ResultSet rs = pstmt.executeQuery();

			// 컬럼명 테이블에 셋팅
			ResultSetMetaData rsm = rs.getMetaData();
			Vector col = new Vector<>();
			for(int i=1; i<=rsm.getColumnCount(); i++){
				col.add(rsm.getColumnName(i));
			}
			DefaultTableModel model = new DefaultTableModel(col, 0);
			table.setModel(model);
			

			table.setRowSorter(new TableRowSorter(model));
			DefaultTableCellRenderer Center = new DefaultTableCellRenderer();
			DefaultTableCellRenderer Right = new DefaultTableCellRenderer();
			TableColumnModel tcmSchedule = table.getColumnModel();
			table.getTableHeader().setReorderingAllowed(false);
			table.getTableHeader().setResizingAllowed(false);
			Center.setHorizontalAlignment(SwingConstants.CENTER);// 우측 정렬
			Right.setHorizontalAlignment(SwingConstants.RIGHT);// / 우측
			
			tcmSchedule.getColumn(0).setPreferredWidth(40);
			tcmSchedule.getColumn(1).setPreferredWidth(30);
			tcmSchedule.getColumn(2).setPreferredWidth(30);
			tcmSchedule.getColumn(3).setPreferredWidth(100);
			tcmSchedule.getColumn(4).setPreferredWidth(30);
			tcmSchedule.getColumn(0).setCellRenderer(Center);
			tcmSchedule.getColumn(1).setCellRenderer(Center);
			tcmSchedule.getColumn(2).setCellRenderer(Center);
			tcmSchedule.getColumn(4).setCellRenderer(Center);
			
			
			while (rs.next()) {
				if (pageCount >= (k * btnCnt - btnCnt) && pageCount < (k * btnCnt)) {
					Vector row = new Vector<>();
						for (int i = 1; i <= rsm.getColumnCount(); i++) {
							row.add(rs.getString(i));
						}
						model.addRow(row);
				}
				pageCount++;

			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	
	
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.add(getLblNewLabel());
			panel.add(getCode());
		}
		return panel;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.add(getLblNewLabel_1());
			panel_1.add(getCodename());
		}
		return panel_1;
	}
	private JTextField getCode() {
		if (code == null) {
			code = new JTextField();
			code.setEditable(false);
			code.setFont(new Font("맑은 고딕", Font.BOLD, 18));
			code.setColumns(10);
		}
		return code;
	}
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("제품 코드");
			lblNewLabel.setFont(new Font("맑은 고딕", Font.BOLD, 18));
		}
		return lblNewLabel;
	}
	private JLabel getLblNewLabel_1() {
		if (lblNewLabel_1 == null) {
			lblNewLabel_1 = new JLabel("제  품  명");
			lblNewLabel_1.setFont(new Font("맑은 고딕", Font.BOLD, 18));
		}
		return lblNewLabel_1;
	}
	private JTextField getCodename() {
		if (codename == null) {
			codename = new JTextField();
			codename.setEditable(false);
			codename.setFont(new Font("맑은 고딕", Font.BOLD, 18));
			codename.setColumns(10);
		}
		return codename;
	}
	private JPanel getPanel_2() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			panel_2.add(getLabel());
			panel_2.add(getPrice());
		}
		return panel_2;
	}
	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("판  매  가");
			label.setFont(new Font("맑은 고딕", Font.BOLD, 18));
		}
		return label;
	}
	private JTextField getPrice() {
		if (price == null) {
			price = new JTextField();
			price.setEditable(false);
			price.setFont(new Font("맑은 고딕", Font.BOLD, 18));
			price.setColumns(10);
		}
		return price;
	}
	private JPanel getPanel_3() {
		if (panel_3 == null) {
			panel_3 = new JPanel();
			panel_3.add(getLabel_1());
			panel_3.add(getEa());
		}
		return panel_3;
	}
	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("판매 수량");
			label_1.setFont(new Font("맑은 고딕", Font.BOLD, 18));
		}
		return label_1;
	}
	private JTextField getEa() {
		if (ea == null) {
			ea = new JTextField();
			ea.setEditable(false);
			ea.setFont(new Font("맑은 고딕", Font.BOLD, 18));
			ea.setColumns(10);
		}
		return ea;
	}
	private JPanel getPanel_4() {
		if (panel_4 == null) {
			panel_4 = new JPanel();
			panel_4.add(getBtnNewButton());
			panel_4.add(getBtnNewButton_1());
		}
		return panel_4;
	}
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("수정");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					mod();
				}
			});
			btnNewButton.setFont(new Font("맑은 고딕", Font.BOLD, 20));
		}
		return btnNewButton;
	}
	private JButton getBtnNewButton_1() {
		if (btnNewButton_1 == null) {
			btnNewButton_1 = new JButton("반품");
			btnNewButton_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					recall();
				}
			});
			btnNewButton_1.setFont(new Font("맑은 고딕", Font.BOLD, 20));
		}
		return btnNewButton_1;
	}
	private JPanel getPanel_5() {
		if (panel_5 == null) {
			panel_5 = new JPanel();
			panel_5.setLayout(new BorderLayout(0, 0));
			panel_5.add(getScrollPane(), BorderLayout.CENTER);
			panel_5.add(getPanel_6(), BorderLayout.SOUTH);
		}
		return panel_5;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}
	private JTable getTable() {
		if (table == null) {
			table = new JTable();
		}
		return table;
	}
	private JPanel getPanel_6() {
		if (panel_6 == null) {
			panel_6 = new JPanel();
		}
		return panel_6;
	}
	private JPanel getPanel_7() {
		if (panel_7 == null) {
			panel_7 = new JPanel();
			panel_7.setLayout(new BorderLayout(0, 0));
			panel_7.add(getPanel(), BorderLayout.NORTH);
			panel_7.add(getPanel_1(), BorderLayout.CENTER);
			panel_7.add(getPanel_2(), BorderLayout.SOUTH);
		}
		return panel_7;
	}
	private JPanel getPanel_8() {
		if (panel_8 == null) {
			panel_8 = new JPanel();
			panel_8.setLayout(new BorderLayout(0, 0));
			panel_8.add(getPanel_3(), BorderLayout.NORTH);
			panel_8.add(getPanel_4(), BorderLayout.SOUTH);
			panel_8.add(getPanel_5(), BorderLayout.WEST);
		}
		return panel_8;
	}
}
